import OSS from 'ali-oss';
import crypto from 'crypto';
import dayjs from 'dayjs';

const config = {
  accessKeyId: process.env.ALIYUN_OSS_ACCESS_KEY_ID,
  accessKeySecret: process.env.ALIYUN_OSS_ACCESS_KEY_SECRET,
  bucket: process.env.ALIYUN_OSS_BUCKET,
  region: process.env.ALIYUN_OSS_REGION,
  dir: process.env.ALIYUN_OSS_DIR || 'images/',
  host: process.env.ALIYUN_OSS_HOST,
};

export function getOssSign() {
  const policyText = {
    expiration: dayjs().add(1, 'h').toISOString(), // 签名有效期1小时
    conditions: [
      ['content-length-range', 0, 1024 * 1024 * 1024], // 上传大小限制1GB，支持大视频文件
      ['starts-with', '$key', config.dir], // 必须上传到指定目录
    ],
  };

  const policyBase64 = Buffer.from(JSON.stringify(policyText)).toString('base64');
  const signature = crypto
    .createHmac('sha1', config.accessKeySecret!)
    .update(policyBase64)
    .digest('base64');

  return {
    accessKeyId: config.accessKeyId,
    policy: policyBase64,
    signature,
    dir: config.dir,
    host: config.host,
    expire: dayjs().add(100, 'y').unix(),
  };
} 